package com.example.temp.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.temp.common.Constants;
import com.example.temp.controller.DAO.SysUserDao;
import com.example.temp.entity.SysUser;
import com.example.temp.exception.ServiceException;
import com.example.temp.mapper.SysUserMapper;
import com.example.temp.utils.PasswordHasher;
import com.example.temp.utils.TokenUtils;
import org.springframework.stereotype.Service;

@Service
public class SysUserService extends ServiceImpl<SysUserMapper,SysUser> {


    public static final Log LOG= Log.get();
    /**
     * 保存添加的用户信息
     * @param user
     * @return
     */
    public boolean saveUser(SysUser user) {
        return saveOrUpdate(user);
    }


    public SysUserDao login(SysUserDao sysUserDao){
        SysUser one=getUserInfo(sysUserDao);
        if(one!=null){
            BeanUtil.copyProperties(one,sysUserDao,true);

            boolean flag = PasswordHasher.verifyPassword(sysUserDao.getPassword(), one.getPassword(), one.getSalt());

            if (flag){
                String token = TokenUtils.genToken(one.getUserId().toString(),one.getPassword());
                sysUserDao.setUserType(one.getUserType());
                sysUserDao.setToken(token);
                return sysUserDao;
            }else{
                throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
            }

        }else {
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }

    /**
     ** 注册接口 数据库查询用户名是否唯一
     ** 唯一则添加到数据库
     ** 不唯一则添加失败
     * @param sysUserDao
     * @return
     */
    public SysUser register(SysUserDao sysUserDao){
        SysUser one=getUserInfo(sysUserDao);

        if (one==null){
            one=new SysUser();
            one.setLoginName(sysUserDao.getLoginName());
            one.setPassword(sysUserDao.getPassword());
            save(one);
        }else {
            throw new ServiceException(Constants.CODE_600,"用户已存在");
        }
        return one;
    }


    private SysUser getUserInfo(SysUserDao sysUserDao){
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", sysUserDao.getLoginName());
//        queryWrapper.eq("password", sysUserDao.getPassword());
        SysUser one;
        //处理异常情况
        try {
            one = getOne(queryWrapper);//从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }
}
